<template>
  <div class="crm">
    <el-button type="primary" class="btn" size="mini" @click="exportExcel"
      >下载模板</el-button
    >
    <el-button type="primary" class="btn" size="mini" @click="addExcel"
      >上传模板</el-button
    >
    <el-button type="primary" class="btn" size="mini" @click="handleAddUser"
      >新增用户</el-button
    >
    <el-button type="primary" class="btn" size="mini" @click="getList"
      >刷新</el-button
    >
    <!-- 表格模板 -->
    <zj-table
      v-loading="loading"
      :columns="columns"
      :data="lists"
      :current-page.sync="currentPage"
      :page-size.sync="pageSize"
      :total="total"
      :selectable="false"
      height="auto"
      :pagination="true"
    />
    <!-- excel上传弹窗部分 -->
    <el-dialog
      title="上传员工列表"
      :visible.sync="excelDialogVisible"
      width="30%"
      center
    >
      <upload-excel-component
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="excelDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <dialogUser v-if="isDialog" @change="handleUserChange" />
  </div>
</template>

<script>
import UploadExcelComponent from "@/components/UploadExcel/index.vue";
import { getUserListApi } from "@/api/user";
import dialogUser from "./components/dialog.vue";
export default {
  components: { UploadExcelComponent, dialogUser },
  data() {
    return {
      isDialog: false,
      excelDialogVisible: false,
      loading: false,
      total: 1,
      currentPage: 1,
      pageSize: 10,
      lists: [],
      columns: Object.freeze([
        {
          label: "姓名",
          prop: "username",
          align: "center",
        },
        {
          label: "户籍所在地",
          prop: "address",
          align: "center",
        },
        {
          label: "手机",
          prop: "phone",
          align: "center",
        },
        {
          label: "性别",
          prop: "gender",
          align: "center",
        },
        {
          label: "民族",
          prop: "nation",
          align: "center",
        },
        {
          label: "年龄",
          prop: "age",
          align: "center",
        },
        {
          width: 300,
          label: "操作",
          actions: [
            {
              id: "follow",
              text: "编辑",
              type: "primary",
              click: this.dialog,
            },
            {
              id: "delete",
              text: "删除",
              type: "danger",
              click: this.delItem,
            },
          ],
        },
      ]),
      //下载excel需要的响应式数据
      downloadLoading: false,
      filename: "员工信息表",
      autoWidth: true,
      bookType: "xlsx",
    };
  },

  async created() {
    this.getList();
  },
  methods: {
    // 关闭
    handleUserChange(flag = false) {
      this.isDialog = false;
      if (flag) this.getList();
    },
    async getList() {
      const res = await getUserListApi();
      this.lists = res.list || [];
    },
    // 点击新增
    handleAddUser() {
      this.isDialog = true;
      console.log("点击了");
      console.log(this.isDialog);
    },
    // 下载模板(excel)
    exportExcel() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        //标题
        const tHeader = ["姓名", "户籍所在地", "手机", "性别", "民族", "年龄"];
        //数据列表
        const filterVal = [
          "name",
          "domicilePlace",
          "phone",
          "gender",
          "nation",
          "age",
        ];
        //后端数据
        const list = this.lists;
        // 这时候性别是0和1区分，需要遍历改变其中每一个
        list.forEach((item) => {
          if (item.gender == 1) {
            item.gender = "男";
          } else {
            item.gender = "女";
          }
        });
        //过滤后的数据
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({
          //导出的数据表头
          header: tHeader,
          //导出的具体数据
          data,
          //文件名
          filename: this.filename,
          // 表格是否要自适应宽度
          autoWidth: this.autoWidth,
          // 导出的文件类型
          bookType: this.bookType,
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    // 上传模板(excel)
    addExcel() {
      // 弹窗
      this.excelDialogVisible = true;
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (isLt1M) {
        return true;
      }

      this.$message({
        message: "Please do not upload files larger than 1m in size.",
        type: "warning",
      });
      return false;
    },
    handleSuccess({ results, header }) {
      console.log(results, "results");
      // 将中文的属性名转化为英文
      const mapInfo = {
        姓名: "name",
        户籍所在地: "domicilePlace",
        手机: "phone",
        性别: "gender",
        民族: "nation",
        年龄: "age",
      };
      const obj = results.map((zhObj) => {
        const enObj = {};
        const zhKeys = Object.keys(zhObj); // ['姓名', '手机号']

        zhKeys.forEach((zhKey) => {
          const enKey = mapInfo[zhKey];

          enObj[enKey] = zhObj[zhKey];
        });
        console.log(enObj, "enObj");
        return enObj;
      });
      this.lists.push(...obj);
    },
    // 编辑
    dialog() {
      this.$message({
        type: "warning",
        message: "该功能尚未开发",
      });
    },
    // 分配权限
    handleRole() {
      this.$message({
        type: "warning",
        message: "该功能尚未开发",
      });
    },
    // 删除
    delItem() {
      this.$message({
        type: "warning",
        message: "该功能尚未开发",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.btn {
  margin-bottom: 20px;
}
</style>
